﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Controls;
using PlanningGIS.Win.Controls;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.Util.Log;

namespace PlanningGIS.Engine.Controls
{
    /// <summary>
    /// 图层属性表控件
    /// </summary>
    public partial class CtlAttributeTable : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlAttributeTable(object hook)
        {
            InitializeComponent();
            if (!DesignMode)
            {
                try
                {
                    _HookHelper = new HookHelper();
                    _HookHelper.Hook = hook;
                    IMapControlEvents2_Event mapctrlEvent = _HookHelper.Hook as IMapControlEvents2_Event;
                    mapctrlEvent.OnMapReplaced += new IMapControlEvents2_OnMapReplacedEventHandler(mapctrlEvent_OnMapReplaced);
                    RegEvent();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorText(ex);
                }
            }
        }

        /// <summary>
        /// 地图关联对象
        /// </summary>
        private IHookHelper _HookHelper = null;

        /// <summary>
        /// tab页名称后缀
        /// </summary>
        private readonly string _tabsuffix = "_tab";

        /// <summary>
        /// tab页容器后缀
        /// </summary>
        private readonly string _pnlsuffix = "_panel";

        /// <summary>
        /// tab页全部移除后是否隐藏停靠窗口
        /// </summary>
        private bool _IsHide = true;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="clsname"></param>
        /// <param name="dataset"></param>
        /// <param name="filter"></param>
        /// <param name="alianame"></param>
        /// <param name="update"></param>
        private void _SetAttributes(string clsname, dynamic dataset, IQueryFilter filter = null, string alianame = "", bool update = false)
        {
            string ctlname = clsname + _pnlsuffix + "_AttributeGridView";
            string tbname = clsname + _tabsuffix;
            if (tabctlAttributes.Tabs.Contains(tbname))
            {
                SuperTabItem tb = (SuperTabItem)tabctlAttributes.Tabs[clsname + _tabsuffix];
                tabctlAttributes.SelectedTab = tb;
                if (update)
                {
                    AttributeGridView grid = (AttributeGridView)tb.AttachedControl.Controls[ctlname];
                    grid.OnCreate(dataset, filter);
                }
            }
            else
            {
                AttributeGridView grid = new AttributeGridView();
                grid.Hook = _HookHelper.Hook;
                grid.Name = ctlname;
                if (grid.OnCreate(dataset, filter)) AddTabPanel(clsname, grid, alianame);
            }
        }

        /// <summary>
        /// 设置图层对象的属性表
        /// </summary>
        /// <param name="featlyr">图层对象</param>
        /// <param name="filter">过滤条件</param>
        /// <param name="update">是否更新表格中的记录</param>
        public void SetAttributes(IFeatureLayer featlyr, IQueryFilter filter = null, bool update = false)
        {
            if (featlyr == null || !featlyr.Valid || featlyr.FeatureClass == null) return;
            string clsname = (featlyr.FeatureClass as IDataset).Name;
            _SetAttributes(clsname, featlyr, filter, featlyr.Name, update);
        }

        /// <summary>
        /// 设置要素类对象的属性表
        /// </summary>
        /// <param name="featcls">要素类对象</param>
        /// <param name="filter">过滤条件</param>
        /// <param name="update">是否更新表格中的记录</param>
        public void SetAttributes(IFeatureClass featcls, IQueryFilter filter = null, bool update = false)
        {
            if (featcls == null) return;
            string clsname = (featcls as IDataset).Name;
            _SetAttributes(clsname, featcls, filter, featcls.AliasName, update);
        }
        
        /// <summary>
        /// 设置要素类集合对象的属性表
        /// </summary>
        /// <param name="featcls">要素类集合对象</param>
        /// <param name="filter">相同的过滤条件</param>
        public void SetAttributes(List<IFeatureClass> featcls, IQueryFilter filter = null)
        {
            if (featcls == null || featcls.Count == 0) return;
            foreach (IFeatureClass cls in featcls) SetAttributes(cls, filter);
        }

        /// <summary>
        /// 设置要素类集合对象的属性表，不同的过滤条件
        /// </summary>
        /// <param name="featcls">要素类集合对象</param>
        public void SetAttributes(Dictionary<IFeatureClass, IQueryFilter> featcls)
        {
            if (featcls == null || featcls.Count == 0) return;
            foreach (KeyValuePair<IFeatureClass, IQueryFilter> kvp in featcls) SetAttributes(kvp.Key, kvp.Value);
        }

        /// <summary>
        /// 添加一个页签
        /// </summary>
        /// <param name="clsname">图层的名称</param>
        /// <param name="control">要添加的控件</param>
        /// <param name="text">显示标题</param>
        public void AddTabPanel(string clsname, Control control, string text = "")
        {
            SuperTabControlPanel panel = new SuperTabControlPanel();
            SuperTabItem tab = new SuperTabItem();
            tab.AttachedControl = panel;
            tab.GlobalItem = false;
            tab.Name = clsname + _tabsuffix;
            tab.Text = string.IsNullOrWhiteSpace(text) ? clsname : text;

            panel.Dock = DockStyle.Fill;
            panel.Location = new System.Drawing.Point(0, 26);
            panel.Name = clsname + _pnlsuffix;
            panel.Size = new System.Drawing.Size(675, 513);
            panel.TabIndex = 1;
            panel.TabItem = tab;
            control.Dock = DockStyle.Fill;
            panel.Controls.Add(control);
            tabctlAttributes.Controls.Add(panel);
            int i = tabctlAttributes.Tabs.Add(tab);
            tabctlAttributes.SelectedTab = tab;
        }

        /// <summary>
        /// 移除指定的标签页
        /// </summary>
        /// <param name="clsname">要素类名称</param>
        /// <param name="ishide">tab页全部移除后是否隐藏停靠窗口</param>
        public void RemoveItem(string clsname, bool ishide = true)
        {
            if (tabctlAttributes.Tabs.Contains(clsname + _tabsuffix))
            {
                tabctlAttributes.Controls[clsname + _pnlsuffix].Controls.Clear();
                tabctlAttributes.Tabs.Remove(clsname + _tabsuffix);     
                tabctlAttributes.Controls.RemoveByKey(clsname + _pnlsuffix);                         
            }
        }

        /// <summary>
        /// 移除所有添加的标签页页签
        /// </summary>
        /// <param name="ishide">tab页全部移除后是否隐藏停靠窗口</param>
        public void RemoveAll(bool ishide = true)
        {
            _IsHide = ishide;
            int tabcnt = tabctlAttributes.Tabs.Count;
            for(int i = tabcnt-1;i>=0;i--)
            {
                BaseItem itm = tabctlAttributes.Tabs[i];
                if (itm is SuperTabItem && itm.Name.EndsWith(_tabsuffix))
                {
                    Control pnl = ((SuperTabItem)itm).AttachedControl;
                    int ccnt = pnl.Controls.Count;
                    for (int j = ccnt - 1; j >= 0; j--)
                    {
                        Control c = pnl.Controls[j];
                        tabctlAttributes.Controls.Remove(c);
                    }
                    tabctlAttributes.Tabs.Remove(itm);
                    tabctlAttributes.Controls.Remove(pnl);
                }
            }
            GC.Collect();
        }

        #region 注册事件

        /// <summary>
        /// 注册事件
        /// </summary>
        private void RegEvent()
        {
            IActiveViewEvents_Event avEvents = _HookHelper.ActiveView as IActiveViewEvents_Event;
            avEvents.ItemDeleted += new IActiveViewEvents_ItemDeletedEventHandler(AvEvents_ItemDeleted);
        }

        /// <summary>
        /// 反注册事件
        /// </summary>
        private void UnRegEvent()
        {
            IActiveViewEvents_Event avEvents = _HookHelper.ActiveView as IActiveViewEvents_Event;
            avEvents.ItemDeleted -= new IActiveViewEvents_ItemDeletedEventHandler(AvEvents_ItemDeleted);
        }

        /// <summary>
        /// 地图改变事件
        /// </summary>
        /// <param name="newMap"></param>
        void mapctrlEvent_OnMapReplaced(object newMap)
        {
            RemoveAll();
            UnRegEvent();
            RegEvent();
        }

        /// <summary>
        /// 移除图层事件
        /// </summary>
        /// <param name="Item"></param>
        void AvEvents_ItemDeleted(object Item)
        {
            string clsname = "";
            if (Item is IFeatureLayer)
                clsname = ((Item as IFeatureLayer).FeatureClass as IDataset).Name;
            else if (Item is IFeatureClass)
                clsname = ((Item as IFeatureClass) as IDataset).Name;
            if (!string.IsNullOrWhiteSpace(clsname)) RemoveItem(clsname);
        }

        #endregion
        
        /// <summary>
        /// 添加字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddField_Click(object sender, EventArgs e)
        {
            if (tabctlAttributes.Tabs.Count == 0) return;
            if (tabctlAttributes.SelectedTab.AttachedControl.Controls.Count == 0) return;
            Control ctl = tabctlAttributes.SelectedTab.AttachedControl.Controls[0];
            if (!(ctl is AttributeGridView)) return;
            AttributeGridView grid = (AttributeGridView)ctl;
            FrmField frm = new FrmField();
            if (frm.ShowDialog(this.ParentForm) != DialogResult.OK) return;
            try
            {
                grid.AddField(frm.NewField);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(this.GetParentForm(), "添加字段失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 弹出下拉菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOperate_PopupOpen(object sender, PopupOpenEventArgs e)
        {
            btnAddField.Enabled = false;
            foreach (BaseItem itm in tabctlAttributes.Tabs)
            {
                if (itm is SuperTabItem)
                {
                    btnAddField.Enabled = true;
                    return;
                }
            }
        }
        
        /// <summary>
        /// 移除tab页时检查是否需要隐藏停靠窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabctlAttributes_TabRemoved(object sender, SuperTabStripTabRemovedEventArgs e)
        {
            HideDockPanel();
        }

        /// <summary>
        /// 隐藏停靠窗口
        /// </summary>
        private void HideDockPanel()
        {
            if (!_IsHide) return;
            if (Parent == null) return;            
            if (tabctlAttributes.Tabs.Count > 0)
            {
                foreach( BaseItem itm in tabctlAttributes.Tabs)
                {
                    if (itm is SuperTabItem) return;
                }
            }
            if (Parent is Bar)
            {
                Parent.Visible = false;
                (Parent as Bar).ParentItem.Refresh();
                (Parent as Bar).ItemsContainer.Refresh();
                (Parent as Bar).RecalcLayout();
            }
        }
    }
}
